<template>
  <div style="width: 100%; height: 100%">
    <!-- 综合执法（队长）---事件指派 -->
    <el-container class="home-qyda" v-if="showlist" v-loading="loading">
      <el-header class="header search-header">
        <el-form
          ref="ruleFormRef"
          class="between-form"
          :model="search"
          :inline="true"
        >
          <div style="flex: 1">
            <el-form-item label="事件类型" prop="eventCode">
              <el-select
                v-model="search.eventCode"
                placeholder="请选择"
                style="min-width: 120px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in typeState.sjlx"
                  :key="item.value"
                  :label="item.key"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="指派状态" prop="assignStatus">
              <el-select
                v-model="search.assignStatus"
                placeholder="是否指派"
                style="min-width: 120px"
                clearable
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="已指派" value="1"></el-option>
                <el-option label="待指派" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="事件等级" prop="eventClass">
              <el-select
                v-model="search.eventClass"
                placeholder="请选择"
                style="min-width: 120px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in typeState.sjdj"
                  :key="item.value"
                  :label="item.key"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="所属社区" prop="orgId">
              <el-select
                v-model="search.orgId"
                placeholder="请选择"
                style="min-width: 120px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in typeState.sssq"
                  :key="item.orgId"
                  :label="item.orgName"
                  :value="item.orgId"
                />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="事件状态" prop="eventStatus">
              <el-select
                v-model="search.eventStatus"
                placeholder="请选择"
                style="min-width: 120px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in typeState.sjzt"
                  :key="item.value"
                  :label="item.key"
                  :value="item.value"
                />
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="设备" prop="deviceId">
              <el-tree-select
                v-model="search.deviceId"
                placeholder="请选择"
                :data="typeState.dwlb"
                :props="customProps"
                :render-after-expand="false"
                style="min-width: 120px"
                node-key="nodeId"
              />
            </el-form-item> -->

            <el-form-item label="指派人员" prop="assignedMemberId">
              <el-select
                v-model="search.assignedMemberId"
                placeholder="请选择"
                style="min-width: 120px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in typeState.czry"
                  :key="item.memberId"
                  :label="item.memberName"
                  :value="item.memberId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="事件时间" prop="eventTime">
              <el-date-picker
                style="width: 340px"
                v-model="search.eventTime"
                type="datetimerange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="handleEventTimeChange"
              />
            </el-form-item>
            <el-form-item label="处置时间" prop="czTime">
              <el-date-picker
                style="width: 340px"
                v-model="search.czTime"
                type="datetimerange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="handleczTimeChange"
              />
            </el-form-item>
          </div>
          <div style="width: 250px">
            <el-form-item>
              <el-button type="primary" class="search-btn" @click="getSearch">
                查询
              </el-button>
              <el-button @click="reset" class="reset-btn">重置</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-header>
      <el-header class="header">
        <div class="header-l">
          <el-icon color="#2263BF">
            <Operation />
          </el-icon>
          <span class="text">事件处置</span>
        </div>
        <div class="header-r">
          <el-button
            link
            type="primary"
            class="self_btns"
            :disabled="selected.length === 0"
            @click="saveExport"
          >
            <img
              style="margin-right: 10px"
              src="../../assets/images/pldc.png"
            />批量导出
          </el-button>
        </div>
      </el-header>
      <el-main>
        <el-container>
          <el-main>
            <el-container>
              <el-main class="container bc-table">
                <el-table
                  :data="objecInfo.tableData"
                  style="width: 100%; height: 100%"
                  @selection-change="changeSelect"
                  row-key="busizEventId"
                >
                  <el-table-column type="selection" width="55" />
                  <el-table-column
                    prop="busizEventId"
                    label="事件编号"
                    width="200"
                  />
                  <el-table-column prop="address" label="事件地址" />
                  <el-table-column prop="eventName" label="事件类型" />
                  <el-table-column prop="eventClass" label="事件等级">
                    <template #default="scope">
                      <span
                        class="level z"
                        v-if="scope.row.eventClass == '重点'"
                        >重点</span
                      >
                      <span
                        class="level w"
                        v-else-if="scope.row.eventClass == '紧急'"
                        >紧急</span
                      >
                      <span class="level" v-else>普通</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="orgName" label="所属社区" />
                  <el-table-column prop="eventStatus" label="指派状态">
                    <template #default="scope">
                      <span
                        style="color: #ae21ff"
                        v-if="scope.row.eventStatusCode == '0'"
                        >{{ scope.row.eventStatus }}</span
                      >
                      <span
                        style="color: #21adff"
                        v-else-if="scope.row.eventStatusCode == '10'"
                        >{{ scope.row.eventStatus }}</span
                      >
                      <span
                        style="color: #21adff"
                        v-else-if="scope.row.eventStatusCode == '99'"
                        >{{ scope.row.eventStatus }}</span
                      >
                      <span
                        style="color: #2aba77"
                        v-else-if="scope.row.eventStatusCode == '101'"
                        >{{ scope.row.eventStatus }}</span
                      >
                    </template>
                  </el-table-column>

                  <el-table-column prop="assignedMember" label="指派人员">
                    <template #default="scope">
                      <span>{{
                        scope.row.assignedMember
                          ? scope.row.assignedMember
                          : "--"
                      }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="eventTime" label="事件时间">
                    <template #default="scope">
                      <span>{{ formatDateTime(scope.row.eventTime) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="handleTime" label="指派时间">
                    <template #default="scope">
                      <span>{{ formatDateTime(scope.row.handleTime) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template #default="scope">
                      <el-button
                        link
                        type="primary"
                        size="small"
                        @click="seedetail(scope.row)"
                        >详情</el-button
                      >
                      <!-- 在这个指派列表，只有待处置的时候，显示完成处置 -->
                      <el-button
                        v-if="scope.row.eventStatusCode == '10'"
                        link
                        type="primary"
                        size="small"
                        @click="changeRow(scope.row.busizEventId, 'cz')"
                        >完成处置</el-button
                      >
                      <el-button
                        v-if="scope.row.eventStatusCode == '0'"
                        link
                        type="primary"
                        size="small"
                        @click="changeRow(scope.row.busizEventId, 'pf')"
                        >指派</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-main>
              <el-footer class="footer mt20">
                <el-pagination
                  v-model:current-page="tableField.pageNo"
                  v-model:page-size="tableField.pageSize"
                  :page-sizes="[10, 20, 30, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  :background="true"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  prev-text="上一页"
                  next-text="下一页"
                />
              </el-footer>
            </el-container>
          </el-main>
        </el-container>
      </el-main>
    </el-container>
    <!-- 处置 -->
    <SelfDialog
      :dialogVisable="dialogVisable"
      :height="currentType == 'pf' ? '320px' : '474px'"
      :title="currentType == 'pf' ? '指派' : '事件处置'"
      @close="close"
      @confirm="confirm"
    >
      <template #default>
        <div class="center_content-pf" v-if="currentType !== 'pf'">
          <cz ref="czref"></cz>
        </div>
        <div class="center_content-pf" v-else>
          <el-form
            ref="ruleFormRef"
            :model="formValue"
            label-width="auto"
            class="ruleForm"
          >
            <el-form-item label="指派处置人员" prop="assignedMemberId">
              <el-select
                v-model="formValue.assignedMemberId"
                placeholder="请选择"
                style="width: 316px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in typeState.czry"
                  :key="item.memberId"
                  :label="item.memberName"
                  :value="item.memberId"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </SelfDialog>
  </div>
</template>

<script setup>
import cz from "@/components/event/cz.vue";
import { ElMessage } from "element-plus";
import { onMounted, ref, reactive, watch } from "vue";
import { getEventList, dispatchEvent, completeEvent } from "@/api/event";
import SelfDialog from "@/components/dialog/dialog.vue";
import { TypeMin } from "@/utils/type.js";
import dayjs from "dayjs";
import { Minxfun } from "@/utils/minxin";

import { TabbarList } from "@/pinia/tabbar.js";
let piniaTab = TabbarList();
const { typeState } = TypeMin();
const {
  handleSizeChange,
  handleCurrentChange,
  tableField,
  total,
  loading,
  formatDateTime,
} = Minxfun();

const customProps = {
  label: "nodeName", // 节点标签对应的字段名
  children: "childrens", // 子节点对应的字段名
  disabled: (data) => {
    // 动态判断是否禁用
    return data.tag == "org"; // 根据 customDisabled 字段禁用
  },
};
const ruleFormRef = ref();
const search = reactive({
  assignedMemberId: "",
  deviceId: "",
  eventCode: "",
  eventStatus: "",
  eventClass: "",
  eventTime: [],
  czTime: [],
  orgId: "",
  assignStatus: "", //0未指派 1已指派
  purpose: "Z", //区分指派和处置
});
const UserId = localStorage.getItem("User");
let dialogVisable = ref(false);
let formValue = ref({ assignedMemberId: "", busizEventId: "" });
let currentType = ref("");
let czref = ref();

let selected = ref([]);
const changeSelect = (rows) => {
  selected.value = rows;
};

onActivated(() => {
  // 组件激活时重新获取数据
  getTableData();
});

onMounted(() => {
  getTableData();
});

const getSearch = () => {
  tableField.value.pageNo = 1;
  getTableData();
};

const reset = () => {
  ruleFormRef.value.resetFields();
  search.eventTime = [];
  search.czTime = [];
  getTableData();
};

watch(
  tableField,
  () => {
    getTableData();
  },
  { deep: true }
);
watch(currentType, (newValue) => {
  if (newValue !== "pf") {
    // 当 currentType 不为 'pf' 时，确保 czref 被重新初始化
    czref.value = null;
  }
});
const handleEventTimeChange = (value) => {
  if (value === null) {
    // 清空时重置为 []
    search.eventTime = [];
  } else {
    search.eventTime = value;
  }
  // 重新加载数据
  getTableData();
};

const handleczTimeChange = (value) => {
  if (value === null) {
    // 清空时重置为 []
    search.czTime = [];
  } else {
    search.czTime = value;
  }
  // 重新加载数据
  getTableData();
};

let objecInfo = reactive({ tableData: [] });

const getTableData = async () => {
  try {
    loading.value = true;
    search.eventTime = search.eventTime || [];
    search.czTime = search.czTime || [];
    const params = {
      ...tableField.value,
      ...search,
      pageNum: tableField.value.pageNo,
      eventTimeStart:
        search.eventTime.length > 0
          ? dayjs(search.eventTime[0]).format("YYYY-MM-DD HH:mm:ss")
          : "",
      eventTimeEnd:
        search.eventTime.length > 0
          ? dayjs(search.eventTime[1]).format("YYYY-MM-DD HH:mm:ss")
          : "",
      handleTimeStart:
        search.czTime.length > 0
          ? dayjs(search.czTime[0]).format("YYYY-MM-DD HH:mm:ss")
          : "",
      handleTimeEnd:
        search.czTime.length > 0
          ? dayjs(search.czTime[1]).format("YYYY-MM-DD HH:mm:ss")
          : "",
    };
    const { data } = await getEventList(params);
    loading.value = false;
    objecInfo.tableData = data.busizEventList;
    total.value = Number(data.total) || 0;
  } catch (e) {
    loading.value = false;
    console.error(e);
  }
};

const changeRow = (value, type) => {
  try {
    console.log("ssssssssssssssss", value, type);
    currentType.value = type;
    if (type === "pf") {
      formValue.value.assignedMemberId = "";
    }
    formValue.value.busizEventId = value;
    dialogVisable.value = true;
    console.log("ssssssssssss", currentType.value);
  } catch (e) {
    console.error(e);
  }
};

const close = () => {
  dialogVisable.value = false;
};

// 确认分派
const confirm = async () => {
  try {
    if (currentType.value == "pf") {
      if (!formValue.value.assignedMemberId) {
        ElMessage.error("请选择派发处置人员");
        return;
      }
      let { data } = await dispatchEvent({
        ...formValue.value,
      });
      console.log(formValue.value);

      dialogVisable.value = false;
    } else {
      let info = czref.value.getValue();
      console.log("完成处置", info.value);
      let { data } = await completeEvent({
        ...info,
        busizEventId: formValue.value.busizEventId,
      });
      console.log({
        ...info,
        busizEventId: formValue.value.busizEventId,
      });
      dialogVisable.value = false;
    }
    getTableData();
  } catch (e) {
    console.error(e);
  }
};

const seedetail = (row) => {
  // 10=待处置，0=待指派,99=已完成
  if (row.eventStatusCode == "10") {
    piniaTab.add({
      name: "处置详情",
      path: "/czdetail",
      icon: "",
      query: {
        busizEventId: row.busizEventId,
      },
      meta: {
        hidden: false,
        title: "",
      },
    });
  } else if (row.eventStatusCode == "0") {
    piniaTab.add({
      name: "指派详情",
      path: "/fpdetail",
      icon: "",
      query: {
        busizEventId: row.busizEventId,
      },
      meta: {
        hidden: false,
        title: "",
      },
    });
  } else {
    piniaTab.add({
      name: "事件详情",
      path: "/eventdetail",
      icon: "",
      query: {
        busizEventId: row.busizEventId,
      },
      meta: {
        hidden: false,
        title: "",
      },
    });
  }
};

const saveExport = async () => {
  try {
    const params = {
      queryOptions: search,
      orderBys: [],
      selectItems: [],
    };
    const config = {
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        withCredentials: true,
      },
      responseType: "blob",
    };
    const response = await axios.post(
      "/data-center/query/composite/export",
      params,
      config
    );
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", "文件.xlsx");
    document.body.appendChild(link);
    link.click();
  } catch (e) {
    console.error(e);
  }
};

let showlist = ref(true);
</script>

<style lang="scss" scoped>
.home-qyda {
  width: 100%;
  height: 100%;

  .header {
    min-height: 36px;
    line-height: 36px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    overflow: hidden;
    margin-bottom: 18px;

    .header-l {
      display: flex;
      align-items: center;

      .text {
        font-family: PingFangSC, PingFang SC;
        font-weight: 600;
        font-size: 16px;
        color: #333333;
        line-height: 22px;
        letter-spacing: 1px;
        text-align: left;
        padding-left: 14px;
      }
    }
  }
}

.el-container {
  height: 100% !important;
  padding: 0 !important;
}

.el-header {
  height: auto !important;
  min-height: 36px !important;
}

.el-main {
  padding: 0 !important;
}

.header-r {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 14px;
  color: #666666;
}

.level {
  display: inline-block;
  text-align: center;
  width: 60px;
  height: 26px;
  background: #e7f6ff;
  border-radius: 4px;
  border: 1px solid rgba(47, 173, 255, 0.32);
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #21adff;
  line-height: 26px;

  &.w {
    background: #ffe6e6;
    color: #ff2121;
    border: 1px solid rgba(255, 47, 47, 0.32);
  }

  &.z {
    background: #fff4e8;
    color: rgba(255, 160, 47, 1);
    border: 1px solid rgba(255, 160, 47, 0.32);
  }
}

.center_content-pf {
  padding: 20px 25px;
}
</style>
